package com.sihan.framework.etm.service.baseData.impl;


import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.framework.exception.BusinessException;
import com.framework.model.ApiResult;
import com.framework.model.PageResult;
import com.framework.mybatis.Condition;
import com.framework.mybatis.service.impl.BaseServiceImpl;
import com.framework.util.JsonUtils;
import com.framework.util.PageUtils;
import com.framework.util.WebUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sihan.framework.etm.common.CacheOperatorInfo;
import com.sihan.framework.etm.common.CommonBiz;
import com.sihan.framework.etm.common.PageRequest;
import com.sihan.framework.etm.common.util.*;
import com.sihan.framework.etm.dto.*;
import com.sihan.framework.etm.dto.baseData.DeviceDTO;
import com.sihan.framework.etm.dto.baseData.DeviceToolConfigDTO;
import com.sihan.framework.etm.dto.baseData.RecordDTO;
import com.sihan.framework.etm.dto.baseData.RecordListIntervalDTO;
import com.sihan.framework.etm.dto.business.DeviceUserConfigDTO;
import com.sihan.framework.etm.entity.EtmDeviceRecord;
import com.sihan.framework.etm.entity.baseData.*;
import com.sihan.framework.etm.entity.business.DeviceUserRel;
import com.sihan.framework.etm.entity.business.ManufactorModel;
import com.sihan.framework.etm.enums.DeviceType;
import com.sihan.framework.etm.mapper.CommonMapper;
import com.sihan.framework.etm.mapper.OrgMapper;
import com.sihan.framework.etm.mapper.baseData.*;
import com.sihan.framework.etm.mapper.business.DeviceUserRelMapper;
import com.sihan.framework.etm.mapper.business.ManufactorMapper;
import com.sihan.framework.etm.service.DeviceComputer;
import com.sihan.framework.etm.service.EtmDeviceMountService;
import com.sihan.framework.etm.service.baseData.DeviceService;
import com.sihan.framework.etm.service.business.ToolPositionService;
import com.sihan.framework.etm.vo.CommonQueryResultVO;
import com.sihan.framework.etm.vo.ToolIocationMode;
import com.sihan.framework.etm.vo.baseData.DeviceRecordVO;
import com.sihan.framework.etm.vo.baseData.DeviceVO;
import com.sihan.framework.etm.vo.baseData.DeviceWithPositionVO;
import com.sihan.framework.etm.vo.business.DeviceUserRelVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.json.simple.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service("deviceService")
public class DeviceServiceImpl extends BaseServiceImpl<DeviceModel, String> implements DeviceService {

    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private ReceiveRecord receiveRecord;

    @Autowired
    private DeviceCoordinateMapper deviceCoordinateMapper;

    @Autowired
    private DeviceToolConfigMapper deviceToolConfigMapper;

    @Autowired
    private DeviceUserRelMapper deviceUserRelMapper;

    @Autowired
    private DeviceBindMapper deviceBindMapper;

    @Autowired
    private CommonBiz commonBiz;

    @Autowired
    private ToolTypeMapper toolTypeMapper;

    @Autowired
    private EtmDeviceRecordMapper etmDeviceRecordMapper;

    @Autowired
    private DeviceComputer deviceComputer;

    @Autowired
    private EtmDeviceMountService mountService;
    @Autowired
    private ManufactorMapper manufactorMapper;

    @Autowired
    private CommonMapper commonMapper;

    @Autowired
    private OrgMapper orgMapper;

    @Override
    public PageResult<DeviceVO> selectPage(DeviceDTO dto) {
        if (!StringUtils.isBlank(dto.getQueryStartTime())) {
            dto.setQueryStartTime(dto.getQueryStartTime() + " 00:00:00:000");
        }
        if (!StringUtils.isBlank(dto.getQueryEndTime())) {
            dto.setQueryEndTime(dto.getQueryEndTime() + " 23:59:59:999");
        }
        String orgIds = (String) CacheOperatorInfo.getMapValue(EtmWebUtil.userId(), null);
        if (StringUtils.isBlank(orgIds)) {
            return PageUtils.toPageResult(new ArrayList<>());
        }
        PageHelper.startPage(dto);
        List<DeviceVO> result = deviceMapper.selectPage(dto, orgIds.split(","));
        if (null != result && !result.isEmpty()) {
            try {
                result.stream().forEach(vo -> {
                    if (null != vo.getElectricityQuantity() && vo.getElectricityQuantity().compareTo(BigDecimal.ZERO) != 0) {

                        vo.setElectricityQuantity(QuantityUtils.formattedQuantity(vo.getVoltage()));

                    }
                });
            } catch (Exception e) {
                log.error("格式化电量异常", e);
            }
        }
        return PageUtils.toPageResult(result);
    }

    @Override
    public PageResult<DeviceVO> selectDevList(PageRequest pageRequest,
                                              String devcode,
                                              String devname,
                                              String orgId) {
        PageHelper.startPage(pageRequest);
        Date startTime = null;
        Date endTime = null;

        try {
            if (null != pageRequest.getQueryStartTime() && null != pageRequest.getQueryEndTime()) {
                startTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(pageRequest.getQueryStartTime());
                endTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(pageRequest.getQueryEndTime());
            }
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }


        List<DeviceVO> result = deviceMapper.selectPages(orgId, devcode, devname, startTime, endTime);
        if (null != result && !result.isEmpty()) {
            try {
                result.stream().forEach(vo -> {
                    if (null != vo.getElectricityQuantity() && vo.getElectricityQuantity().compareTo(BigDecimal.ZERO) != 0) {
                        if (vo.getVoltage().compareTo(new BigDecimal("3.45")) >= 0) {
                            vo.setElectricityQuantity(vo.getElectricityQuantity().multiply(new BigDecimal(100)));
                        } else {
                            vo.setElectricityQuantity(BigDecimal.ZERO);
                        }
                    } else {
                        if (vo.getVoltage().compareTo(new BigDecimal("3.6")) >= 0) {
                            vo.setElectricityQuantity(new BigDecimal(90));
                        } else if (vo.getVoltage().compareTo(new BigDecimal("3.58")) >= 0) {
                            vo.setElectricityQuantity(new BigDecimal(70));
                        } else if (vo.getVoltage().compareTo(new BigDecimal("3.55")) >= 0) {
                            vo.setElectricityQuantity(new BigDecimal(50));
                        } else if (vo.getVoltage().compareTo(new BigDecimal("3.52")) >= 0) {
                            vo.setElectricityQuantity(new BigDecimal(30));
                        } else if (vo.getVoltage().compareTo(new BigDecimal("3.51")) >= 0) {
                            vo.setElectricityQuantity(new BigDecimal(20));
                        } else if (vo.getVoltage().compareTo(new BigDecimal("3.50")) >= 0) {
                            vo.setElectricityQuantity(new BigDecimal(10));
                        } else if (vo.getVoltage().compareTo(new BigDecimal("3.45")) <= 0) {
                            vo.setElectricityQuantity(new BigDecimal(0));
                        }
                    }
                });
            } catch (Exception e) {
                log.error("格式化电量异常", e);
            }
        }
        return PageUtils.toPageResult(result);
    }

    @SuppressWarnings("unchecked")
    @Transactional
    @Override
    public synchronized ApiResult<?> saveOrUpdateDevice(DeviceDTO device) {
        //检查输入的属性是否正确
        if (!StringUtils.isBlank(device.getName()) && device.getName().length() > 50) {
            throw new BusinessException("设备名称不能超过50个汉字");
        }
        if (StringUtils.isBlank(device.getCode())) {
            throw new BusinessException("设备编号不能为空");
        }
        if (!StringUtils.isBlank(device.getImeiCode()) && device.getImeiCode().length() > 50) {
            throw new BusinessException("设备IMEI号不能超过50个字符");
        }

        DeviceModel data = null;
        Date date = null;
        if (null != device.getProductDate()) {
            date = DateUtils.getInstance().getDateByStr(device.getProductDate(), DateUtils.getInstance().SDF);
        }
        ToolTypeModel toolType = toolTypeMapper.selectById(device.getTypeId());
        device.setToolCode(commonBiz.genarateToolCode(toolType.getCode(), 1).get(0));


        if (StringUtils.isBlank(device.getId())) {
            //判断是否有重复的
            data = deviceMapper.selectOne(new Condition<DeviceModel>()
                    .eq("is_delete", 0)
                    .eq("code", device.getCode())
                    .OR()
                    .eq("is_delete", 0)
                    .eq("imei_code", device.getImeiCode())
                    .OR()
                    .eq("is_delete", 0)
                    .eq("communication_code", device.getCommunicationCode()));
        } else {
            data = deviceMapper.selectOne(new Condition<DeviceModel>().
                    eq("code", device.getCode())
                    .eq("is_delete", 0)
                    .neq("id", device.getId())
                    .OR()
                    .eq("imei_code", device.getImeiCode())
                    .eq("is_delete", 0)
                    .neq("id", device.getId())
                    .OR()
                    .eq("communication_code", device.getCommunicationCode())
                    .eq("is_delete", 0)
                    .neq("id", device.getId()));
        }

        if (null != data) {
            throw new BusinessException("编号重复");
        }
        DeviceModel d = new DeviceModel();

        BeanUtils.copyProperties(device, d);
        if (StringUtils.isBlank(d.getId())) {
            d.setManufactorId(device.getManufactorId());
            d.setCreateTime(new Date());
            d.setCreateUser(WebUtils.username());
            d.setDeviceState(-2);
            d.setProducteDate(date);
            deviceMapper.insert(d);
        } else {
            d = deviceMapper.selectById(device.getId());
            d.setOrgId(device.getOrgId());
            d.setVoltageGrade(device.getVoltageGrade());
            d.setCommunicationCode(device.getCommunicationCode());
            d.setImeiCode(device.getImeiCode());
            d.setName(device.getName());
            d.setCode(device.getCode());
            d.setHitchACode(device.getHitchACode());
            d.setHitchBCode(device.getHitchBCode());
            d.setHitchCCode(device.getHitchCCode());
            d.setHitchDCode(device.getHitchDCode());
            d.setManufactorId(device.getManufactorId());
            if (null != device.getInitialLng()) {
                d.setInitialLng(device.getInitialLng());
            }
            if (null != device.getInitialLat()) {
                d.setInitialLat(device.getInitialLat());
            }
            d.setInitialHeight(device.getInitialHeight());
            d.setLastUpdateTime(new Date());
            d.setProducteDate(date);
            d.setLastUpdateUser(WebUtils.username());
            deviceMapper.updateAllColumnsById(d);
        }
        return ApiResult.success();
    }

    @SuppressWarnings("unchecked")
    @Transactional
    @Override
    public synchronized ApiResult<?> saveOrDeviceExcelDTO(List<DeviceExcelDTO> dto) {
        List<Integer> ints = new ArrayList<>();
        Date date = new Date();
        for (DeviceExcelDTO dev : dto) {
            if ("331".equals(dev.getTypeId()) || "4001".equals(dev.getTypeId())) {
                DeviceDTO device = new DeviceDTO();
                BeanUtils.copyProperties(dev, device);
                String imeiCode = dev.getImeiCode();
                String substring = imeiCode.substring(7, 15);
                device.setCommunicationCode(substring);
                if ("331".equals(dev.getTypeId())) {
                    device.setCode("RTK-" + dev.getCommunicationCode());
                    device.setName("智能型接地线-" + dev.getCommunicationCode());
                } else {
                    device.setCode("SD-" + dev.getCommunicationCode());
                    device.setName("输电型接地线-" + dev.getCommunicationCode());
                }
                device.setVoltageGrade("5");
                //检查输入的属性是否正确
                if (!StringUtils.isBlank(device.getImeiCode()) && device.getImeiCode().length() > 50) {
                    throw new BusinessException("设备IMEI号不能超过50个字符");
                }
                DeviceModel data = null;
                ToolTypeModel toolType = toolTypeMapper.selectById(device.getTypeId());
                device.setToolCode(commonBiz.genarateToolCode(toolType.getCode(), 1).get(0));

                if (StringUtils.isBlank(device.getId())) {
                    //判断是否有重复的
                    data = deviceMapper.selectOne(new Condition<DeviceModel>()
                            .eq("is_delete", 0)
                            .eq("code", device.getCode())
                            .OR()
                            .eq("is_delete", 0)
                            .eq("imei_code", device.getImeiCode())
                            .OR()
                            .eq("is_delete", 0)
                            .eq("communication_code", device.getCommunicationCode()));
                } else {
                    data = deviceMapper.selectOne(new Condition<DeviceModel>()
                            .eq("code", device.getCode())
                            .eq("is_delete", 0)
                            .neq("id", device.getId())
                            .OR()
                            .eq("imei_code", device.getImeiCode())
                            .eq("is_delete", 0)
                            .neq("id", device.getId())
                            .OR()
                            .eq("communication_code", device.getCommunicationCode())
                            .eq("is_delete", 0)
                            .neq("id", device.getId()));
                }

                if (null != data) {
                    ints.add(dev.getRowNum());
                    throw new BusinessException("编号重复");
                }
                DeviceModel d = new DeviceModel();

                BeanUtils.copyProperties(device, d);
                //查生产厂家表
                String manufatorId = commonMapper.selectManufatorId(dev.getManufactorId());
                if (null == manufatorId || "".equals(manufatorId)) {
                    ints.add(dev.getRowNum());
                    throw new BusinessException("未知厂商,请先创建对应厂商再导入");
                }
                d.setManufactorId(manufatorId);
                String orgId = orgMapper.selectOneByNameString(dev.getOrgId());
                if (null == orgId || "".equals(orgId)) {
                    ints.add(dev.getRowNum());
                    throw new BusinessException("未知组织,请先创建对应组织再导入");
                }
                d.setOrgId(orgId);
                if (StringUtils.isBlank(d.getId())) {
                    d.setCreateTime(new Date());
                    d.setCreateUser(WebUtils.username());
                    d.setDeviceState(-2);
                    d.setProducteDate(date);
                    deviceMapper.insert(d);
                } else {
                    d = deviceMapper.selectById(device.getId());
                    d.setOrgId(device.getOrgId());
                    d.setVoltageGrade(device.getVoltageGrade());
                    d.setCommunicationCode(device.getCommunicationCode());
                    d.setImeiCode(device.getImeiCode());
                    d.setName(device.getName());
                    d.setCode(device.getCode());
                    d.setHitchACode(device.getHitchACode());
                    d.setHitchBCode(device.getHitchBCode());
                    d.setHitchCCode(device.getHitchCCode());
                    d.setHitchDCode(device.getHitchDCode());
                    d.setInitialLng(device.getInitialLng());
                    d.setInitialLat(device.getInitialLat());
                    d.setInitialHeight(device.getInitialHeight());
                    d.setLastUpdateTime(new Date());
                    d.setProducteDate(date);
                    d.setLastUpdateUser(WebUtils.username());
                    deviceMapper.updateAllColumnsById(d);
                }
            }
            if (ints.size() > 0) {
                return ApiResult.success("导入数据出现重复-行数：" + ints.toString());
            }
        }

        return ApiResult.success();
    }

    @Override
    public DeviceVO selectDeviceById(String id) {
        return deviceMapper.selectDetailInfo(id);
    }

    @Override
    public List<String> getAllDeviceCode(Integer stat) {
        return deviceMapper.getAllDeviceCode(stat);
    }

    @SuppressWarnings("unchecked")
    @Override
    @Transactional
    public ApiResult<?> saveOrUpdateDeviceToolConfig(DeviceToolConfigDTO dto) {
        if (null != dto) {
            deviceToolConfigMapper.delete(new Condition<>().eq("device_id", dto.getDeviceId()));
            dto.getDatas().stream().forEach(data -> {
                DeviceToolConfig config = new DeviceToolConfig();
                config.setDeviceId(dto.getDeviceId());
                if (data.getQuantity() == null || data.getQuantity().compareTo(new BigDecimal(99999)) > 0) {
                    throw new BusinessException("配置数量太大");
                }
                config.setQuantity(data.getQuantity());
                config.setStandardId(data.getStandardId());
                deviceToolConfigMapper.insert(config);
            });
        }
        return ApiResult.success();
    }

    @SuppressWarnings("unchecked")
    @Override
    public ApiResult<?> selectDeviceToolConfigById(String id) {
        List<DeviceToolConfig> result = deviceToolConfigMapper.selectList(new Condition<>().eq("device_id", id));
        if (null == result || result.isEmpty()) {
            result = new ArrayList<DeviceToolConfig>();
            DeviceToolConfig config = new DeviceToolConfig();
            result.add(config);
        }
        return ApiResult.success(result);
    }

    @Override
    public ApiResult<?> deleteDevice(String id) {
        DeviceModel device = deviceMapper.selectById(id);
        if (null == device) {
            return ApiResult.fail("传入参数有误");
        }

        device.setIsDelete(1);
        deviceMapper.updateById(device);

        return ApiResult.success();
    }

/*    @Override
    public void receiveRecord(Map<String, String> requestMap) {
        String recordData = requestMap.get("payload");
        try {
            Map body = JsonUtils.readFromJson(recordData, HashMap.class);
            System.out.println("body数据：" + body.toString());
            if (body.get("code") != null && body.get("code").equals(16385) || body.get("type") != null && body.get("type").equals(4000)) {
                String deviceCode = body.get("code") != null && body.get("code").equals(16385) ? body.get("deviceId").toString() : body.get("deviceID").toString();
                List<DeviceModel> devices = deviceMapper.selectList(new Condition(new DeviceModel()).eq("communication_code", deviceCode).eq("is_delete", 0));
                for (DeviceModel device : devices) {
                    if (device != null) {
                        BigDecimal electricityPercent = deviceComputer.calculateAndUpdateVoltage(body);
                        EtmDeviceRecord record = EtmDeviceRecord.builder()
                                .deviceId(device.getId())
                                .deviceCode(deviceCode)
                                .rawData(recordData)
                                .createTime(new Date())
                                .electricityPercent(electricityPercent == null ? null : electricityPercent.doubleValue())
                                .build();

                        if (device.getTypeId().equals(DeviceType.WarningSign) && body.get("code").equals(16385)) {
                            if (device.getInitialLng() == null || device.getInitialLat() == null || device.getInitialHeight() == null) {
                                device.setInitialLat((int) body.get("latitude") / 1000000.0);
                                device.setInitialLng((int) body.get("longitude") / 1000000.0);
                                device.setInitialHeight((int) body.get("height") / 10.0);
                                deviceMapper.updateById(device);
                                record.setPositionOffset((double) 0);
                            } else {
                                record.setPositionOffset(DistanceComputer.compute(
                                        DistanceComputer.Point.builder()
                                                .height(device.getInitialHeight())
                                                .longitude(device.getInitialLng())
                                                .latitude(device.getInitialLat())
                                                .build(),
                                        DistanceComputer.Point.builder()
                                                .height((int) body.get("height") / 10.0)
                                                .longitude((int) body.get("longitude") / 1000000.0)
                                                .latitude((int) body.get("latitude") / 1000000.0)
                                                .build()
                                ));
                            }

                        }
                        if (device.getTypeId().equals(DeviceType.GroundWire) && body.get("type").equals(4000)) {

                            String statusString = new StringBuffer(body.get("status").toString()).reverse().toString();
                            //statusString 包含1说明有挂接项
                            //处理三项数据

                            if ("0000000000000000".equals(statusString)) {

                                if (body.get("sendID0").toString().equals(device.getHitchACode())) {
                                    record.setHitchA(true);
                                } else if ("0".equals(body.get("sendID0").toString())) {
                                    record.setHitchA(false);
                                }
                                if (body.get("sendID1").toString().equals(device.getHitchBCode())) {
                                    record.setHitchB(true);
                                } else if ("0".equals(body.get("sendID1").toString())) {
                                    record.setHitchB(false);
                                }
                                if (body.get("sendID2").toString().equals(device.getHitchCCode())) {
                                    record.setHitchC(true);
                                } else if ("0".equals(body.get("sendID2").toString())) {
                                    record.setHitchC(false);
                                }
                            }

                            if (statusString.contains("1")) {
                                Set set = body.keySet();
                                for (Object s : set) {
                                    String key = s.toString();
                                    if (key.contains("sendID")) {
                                        String value = body.get(key).toString();
                                        if (value.equals(device.getHitchACode())) {
                                            int index = Integer.parseInt(key.replace("sendID", ""));
                                            record.setHitchA(statusString.charAt(index) == '1');
                                        }
                                        if (value.equals(device.getHitchBCode())) {
                                            int index = Integer.parseInt(key.replace("sendID", ""));
                                            record.setHitchB(statusString.charAt(index) == '1');
                                        }
                                        if (value.equals(device.getHitchCCode())) {
                                            int index = Integer.parseInt(key.replace("sendID", ""));
                                            record.setHitchC(statusString.charAt(index) == '1');
                                        }
                                    }
                                }
                            }

                            //根据 record 与 device 做工器具状态 做记录
                            mountService.insertDeviceMount(record, device);
                        }

                        etmDeviceRecordMapper.insert(record);
                    }
                }
            } else if (body.containsKey("data")) {
                String data = (String) body.get("data");
                ToolIocationMode mode = JsonUtils.readFromJson(data, ToolIocationMode.class);
                newReceiveRecord(mode,data);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }*/


    @Override
    public void receiveRecord(JSONObject jsonObject,Date date) {
        Object recordData = jsonObject.get("payload");
        try {

            Map body = JsonUtils.readFromJson((String) recordData, HashMap.class);
            if (body.get("code") != null && body.get("code").equals(16385) || body.get("type") != null && body.get("type").equals(4000)) {
                //旧版协议
                String deviceCode = body.get("code") != null && body.get("code").equals(16385) ? body.get("deviceId").toString() : body.get("deviceID").toString();
                List<DeviceModel> devices = deviceMapper.selectList(new Condition(new DeviceModel()).eq("communication_code", deviceCode).eq("is_delete", 0));
                for (DeviceModel device : devices) {
                    if (device != null) {
                        BigDecimal electricityPercent = deviceComputer.calculateAndUpdateVoltage(body);
                        BigDecimal lng = null;
                        BigDecimal lnt =  null;
                        try {
                            String coorOld = body.get("longitude")+","+body.get("latitude");
                            String coors = sgmap.coorTrans(coorOld);
                            // 创建 ObjectMapper 实例
                            ObjectMapper objectMapper = new ObjectMapper();
                            JsonNode rootNode = objectMapper.readTree(coors);
                            // 获取 "value" 数组
                            JsonNode valueArray = rootNode.path("value");
                            // 遍历数组并获取 x 和 y 的值
                            for (JsonNode item : valueArray) {
                                lng = item.path("x").decimalValue();
                                lnt = item.path("y").decimalValue();
                            }
                        } catch(Exception e) {
                            e.printStackTrace();
                        }
                        device.setInitialLat(lnt);
                        device.setInitialLng(lng);
                        device.setInitialHeight(BigDecimal.valueOf((int) body.get("height") / 10.0));
                        EtmDeviceRecord record = EtmDeviceRecord.builder()
                                .deviceId(device.getId())
                                .deviceCode(deviceCode)
                                .rawData(recordData.toString())
                                .createTime(date)
                                .electricityPercent(electricityPercent == null ? null : electricityPercent.doubleValue())
                                .positionalAccuracy(Integer.parseInt((String) body.get("precision")))
                                .build();
                        if (device.getTypeId().equals(DeviceType.GroundWire) && body.get("type").equals(4000)) {

                            String statusString = new StringBuffer(body.get("status").toString()).reverse().toString();
                            //statusString 包含1说明有挂接项
                            //处理三项数据
                            System.out.println("开始处理三项数据");
                            if ("0000000000000000".equals(statusString)) {
                                if (body.get("sendID0").toString().equals(device.getHitchACode())) {
                                    record.setHitchA(true);
                                } else if ("0".equals(body.get("sendID0").toString())) {
                                    record.setHitchA(false);
                                }
                                if (body.get("sendID1").toString().equals(device.getHitchBCode())) {
                                    record.setHitchB(true);
                                } else if ("0".equals(body.get("sendID1").toString())) {
                                    record.setHitchB(false);
                                }
                                if (body.get("sendID2").toString().equals(device.getHitchCCode())) {
                                    record.setHitchC(true);
                                } else if ("0".equals(body.get("sendID2").toString())) {
                                    record.setHitchC(false);
                                }
                            }

                            if (statusString.contains("1")) {
                                Set set = body.keySet();
                                for (Object s : set) {
                                    String key = s.toString();
                                    if (key.contains("sendID")) {
                                        String value = body.get(key).toString();
                                        if (value.equals(device.getHitchACode())) {
                                            int index = Integer.parseInt(key.replace("sendID", ""));
                                            record.setHitchA(statusString.charAt(index) == '1');
                                        }
                                        if (value.equals(device.getHitchBCode())) {
                                            int index = Integer.parseInt(key.replace("sendID", ""));
                                            record.setHitchB(statusString.charAt(index) == '1');
                                        }
                                        if (value.equals(device.getHitchCCode())) {
                                            int index = Integer.parseInt(key.replace("sendID", ""));
                                            record.setHitchC(statusString.charAt(index) == '1');
                                        }
                                    }
                                }
                            }
                            //根据 record 与 device 做工器具状态 做记录
                            mountService.insertDeviceMount(record, device,date);
                        }
                        etmDeviceRecordMapper.insert(record);
                    }
                }
            } else if (body.containsKey("data")) {
                //新版协议
                String data = JsonUtils.toJsonString(body.get("data"));
                ToolIocationMode mode = JsonUtils.readFromJson(data, ToolIocationMode.class);
                receiveRecord.newReceiveRecord(mode, data, date);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @Override
    public PageResult<DeviceRecordVO> recordList(RecordDTO dto) {
        Page<DeviceRecordVO> result = PageHelper.startPage(dto);
        List<RecordDTO> list = new ArrayList();
        list.add(dto);
        etmDeviceRecordMapper.selectRecorderList(list);
        return PageUtils.toPageResult(result);
    }

    @Override
    public List<DeviceWithPositionVO> recordListInterval(RecordListIntervalDTO dto) {

        List<RecordDTO> list = new ArrayList();


        if (dto.getCodeList() == null || dto.getStartTime() == null || dto.getEndTime() == null) {
            return new ArrayList<>();
        }

        return deviceCoordinateMapper.deviceWithPosition(dto.getCodeList(), dto.getStartTime(), dto.getEndTime());
    }

    @Override
    public PageResult<DeviceModelDTO> getListDeviceModelDTO(PageRequest pageRequest,
                                                            String deviceName,
                                                            String deviceCode,
                                                            Integer toolType) {
        PageHelper.startPage(pageRequest);
        String orgIds = (String) CacheOperatorInfo.getMapValue(EtmWebUtil.userId(), null);
        /*if (StringUtils.isBlank(orgIds)) {
            return PageUtils.toPageResult(new ArrayList<DeviceModelDTO>());
        }*/
        List<DeviceModelDTO> listDeviceModelDTO = deviceMapper.getListDeviceModelDTO(deviceName, deviceCode, null, toolType);
//        //对电量进行计算
//        if (listDeviceModelDTO.size() > 0) {
//            for (DeviceModelDTO devDTO : listDeviceModelDTO) {
//                if (null != devDTO.getVoltage()) {
//                    BigDecimal bigDecimal = QuantityUtils.formattedQuantity(devDTO.getVoltage());
//                    devDTO.setElectricityPercent(bigDecimal);
//                }
//            }
//        }
        return PageUtils.toPageResult(listDeviceModelDTO);
    }

    @Override
    public PageResult<DeviceModelDTO> wxGetListDeviceModelDTO(PageRequest pageRequest, String deviceCode) {
        PageHelper.startPage(pageRequest);
        String orgIds = (String) CacheOperatorInfo.getMapValue(EtmWebUtil.userId(), null);
        if (StringUtils.isBlank(orgIds)) {
            return PageUtils.toPageResult(new ArrayList<DeviceModelDTO>());
        }
        List<DeviceModelDTO> listDeviceModelDTO = deviceMapper.wxGetListDeviceModelDTO(null, deviceCode);
//        //对电量进行计算
//        if (listDeviceModelDTO.size() > 0) {
//            for (DeviceModelDTO devDTO : listDeviceModelDTO) {
//                if (null != devDTO.getVoltage()) {
//                    BigDecimal bigDecimal = QuantityUtils.formattedQuantity(devDTO.getVoltage());
//                    devDTO.setElectricityPercent(bigDecimal);
//                }
//            }
//        }
        return PageUtils.toPageResult(listDeviceModelDTO);
    }

    @Override
    public DeviceModelDTO getOneDeviceModelDTO(String deviceId) {
        if (null == deviceId) {
            return null;
        }
        DeviceModelDTO dev = deviceMapper.getOneDeviceModelDTO(deviceId);
        //dev.setElectricityPercent(QuantityUtils.formattedQuantity(dev.getVoltage()));
        return dev;
    }

    @Override
    public Boolean addManufator(ManufactorModel manufactorModel) {

        return manufactorMapper.insert(manufactorModel);
    }

    @Override
    public PageResult<EtmDeviceMountDTO> queryDeviceRunningData(DevicePageDTO dto) {
        if (!StringUtils.isBlank(dto.getStartDate())) {
            dto.setStartDate(dto.getStartDate() + " 00:00:00:000");
        }
        if (!StringUtils.isBlank(dto.getEndDate())) {
            dto.setEndDate(dto.getEndDate() + " 23:59:59:999");
        }
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        List<EtmDeviceMountDTO> result = etmDeviceRecordMapper.queryDeviceRunningDataByDeviceId(
                dto.getDeviceId(),dto.getStartDate(),dto.getEndDate());
        return PageUtils.toPageResult(result);
    }

    @Override
    public PageResult<EtmDeviceMountDTO> queryDevicePositionData(DevicePageDTO dto) {
        if (!StringUtils.isBlank(dto.getStartDate())) {
            dto.setStartDate(dto.getStartDate() + " 00:00:00:000");
        }
        if (!StringUtils.isBlank(dto.getEndDate())) {
            dto.setEndDate(dto.getEndDate() + " 23:59:59:999");
        }
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        List<EtmDeviceMountDTO> result = etmDeviceRecordMapper.queryDevicePositionDataByDeviceId(
                dto.getDeviceId(),dto.getStartDate(),dto.getEndDate());
        return PageUtils.toPageResult(result);
    }


    @SuppressWarnings("unchecked")
    @Override
    public ApiResult<?> saveOrUpdateDeviceUserConfig(DeviceUserConfigDTO dto) {
        if (null != dto) {
            deviceUserRelMapper.delete(new Condition<>().eq("device_id", dto.getDeviceId()));
            dto.getUserIds().stream().forEach(data -> {
                DeviceUserRel config = new DeviceUserRel();
                config.setDeviceId(dto.getDeviceId());
                config.setUserId(data);
                deviceUserRelMapper.insert(config);
            });
            //commonSendInfo.sendDeviceUsersRel(dto.getDeviceId());
        }
        return ApiResult.success();
    }

    @Override
    public ApiResult<?> selectDeviceUserConfigById(String id) {
        DeviceUserRelVO vo = new DeviceUserRelVO();
        vo.setDeviceId(id);
        @SuppressWarnings("unchecked")
        List<DeviceUserRel> result = deviceUserRelMapper.selectList(new Condition<>().eq("device_id", id));
        if (null != result && !result.isEmpty()) {
            vo.setUserIds(result.stream().map(DeviceUserRel::getUserId).collect(Collectors.toList()));
        }
        return ApiResult.success(vo);
    }

    @SuppressWarnings("unchecked")
    @Override
    @Transactional
    public void bindOrUnbindDevice(String id, Boolean bindOperate) {
        DeviceModel device = deviceMapper.selectById(id);
        if (null == device) {
            new BusinessException("参数错误");
        }

        deviceMapper.updateById(device);

        if (!bindOperate) {
            DeviceBindRecordModel record = deviceBindMapper.selectOne(new Condition<DeviceBindRecordModel>().
                    eq("device_id", id).isNuLL("unbind_time").order("bind_time", "DESC"));
            if (null != record) {
                record.setUnbindTime(new Date());
                deviceBindMapper.updateById(record);
            }
        } else {
            DeviceBindRecordModel record = new DeviceBindRecordModel();
            record.setBindTime(new Date());
            record.setDeviceId(id);
            deviceBindMapper.insert(record);
        }

    }
}
